<?php
namespace App\Repositories\Eloquent;
use App\Models\Category;
use App\Repositories\Contracts\CategoryInterface;
class CategoryServiceRepository implements CategoryInterface{
    public function all($columns = array('*')){
        return Category::all($columns);
    }
    public function deleteId($id){
        $del = Category::destroy($id);
        if( $del ){
            $data = [
                'status' => 1,
                'msg'    => '删除成功！',
            ];
        }else{
            $data = [
                'status' => 0,
                'msg'    => '删除失败！',
            ];
        }
        return response()->json($data);
    }
    /**
     * 递归获取子菜单
     * @param $menus
     * @param int $pid
     */
    public function sortMenu($menus,$pid=0){
        $array = [];
        if( empty($menus) ) return '';
        foreach( $menus as $k => $v ){
            if( $v['pid'] == $pid ){
                $array[$k] = $v;
                $array[$k]['child'] = self::sortMenu($menus,$v['id']);
            }
        }
        return $array;
    }
    /**
     * 子菜单排序并缓存
     * @param $menus
     */
    public function sortMenuSetCache(){
        $menus = Category::orderBy('sort','desc')->get()->toArray();
        if($menus){
            $menuList = self::sortMenu($menus);
            foreach( $menuList as $k => &$v ){
                if($v['child']){
                    $sort = array_column($v['child'],'sort');
                    array_multisort($sort,SORT_DESC,$v['child']);
                }
            }
            // 缓存菜单数据
            return $menuList;
        }
        return '';
    }

    public function getMenuList(){
        // 判断菜单数据是否存在
        return self::sortMenuSetCache();
    }
}